package com.itheima.controller;

import com.aili.heima.AliyunOSSOperator;
import com.aili.heima.AliyunOSSProperties;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;
    private File saveFile = new File("E:\\develop\\project\\tlias-web-management\\img\\");

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) throws Exception {
////        本地存储
//        String filename = file.getOriginalFilename();
//        long size = file.getSize();
//        File[] files = saveFile.listFiles();
//        for (File f : files) {
//            if(f.isFile() ){
//                long length = f.length();
//                if(length == size){
//                    String name = "http://127.0.0.1:8080/"+ f.getName();
//                    return Result.success(name);
//                }
//            }
//        }
//        String extendName = filename.substring(filename.lastIndexOf('.'));
//        String uuid = UUID.randomUUID().toString();
//        String newFilename = uuid + extendName;
//        file.transferTo(new File("E:\\develop\\project\\tlias-web-management\\img\\" + newFilename));
//        String httpPath = "http://127.0.0.1:8080/" + newFilename;
//        return Result.success(httpPath);
//
        // aliyunOssDeleteOper.delete("2025/09/2e1880ea-96fa-485d-9d30-5d936bb6d696.jpg");

//        阿里图像上传
        String endpoint = aliyunOSSProperties.getEndpoint();
        String bucketName = aliyunOSSProperties.getBucketName();
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        Map<String, Long> maps = aliyunOSSOperator.list();
        Set<Map.Entry<String, Long>> entries = maps.entrySet();
        for (Map.Entry<String, Long> entry : entries) {
            String filename = String.valueOf(entry.getKey());
            if (size == entry.getValue()) {
                return Result.success(endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename);
            }
        }
        String upload = aliyunOSSOperator.upload(file.getBytes(), originalFilename);
        log.info("文件上传");
        //获取emp表中的image数据
        return Result.success(upload);

    }
}
